import { FileBuffer } from './FileBuffer';
import { FilePathGenerator } from '../file_manager/FilePathGenerator';
import { FileManager } from '../file_manager/FileManager';
import { BufferHint, IBufferCreator } from './IBufferCreator';
import { MemBuffer } from './MemBuffer';

/**
 * basePath是这个BufferCreator创建的buffer的根目录
 * @param basePath
 * @returns
 */
export function createBufferCreator(accountKey: string): IBufferCreator {
  let basePath = FilePathGenerator.buffDir;
  const dirPath = `${basePath}/${accountKey}`
  FileManager.createDirSync(dirPath);
  let index = 0;
  const bufferCreator: IBufferCreator = {
    createBuffer(hint: BufferHint) {
      if (hint.useFile || hint.size >= 2 * 1024 * 1024) { // 数据较大使用文件
        index += 1;
        const filePath = `${dirPath}/${index}.buf`;
        FileManager.createFileSync(filePath);
        return new FileBuffer(filePath);
      } else {
        return new MemBuffer();
      }
    }
  }
  return bufferCreator;
}